import { FetchResult, Observable } from "@apollo/client";
import { message } from "antd";
import { GraphQLError } from "graphql/error/GraphQLError";
// import { showMessage } from 'react-native-flash-message';

import { ErrorMatchHandler } from "./error-handler";
export interface GraphQLErrorMatchHandler extends ErrorMatchHandler {
  match(error: GraphQLError): boolean;

  handle(error: GraphQLError): Observable<FetchResult> | void;
}

export class UnauthorizedErrorHandler implements GraphQLErrorMatchHandler {
  match(error: GraphQLError): boolean {
    return error.extensions?.code === "unauthorized";
  }

  handle(
    error: GraphQLError
  ): void | Observable<
    FetchResult<Record<string, any>, Record<string, any>, Record<string, any>>
  > {
    // @ts-ignore
    console.log(error);
  }
}

export class ForbiddenErrorHandler implements GraphQLErrorMatchHandler {
  match(error: GraphQLError): boolean {
    return error.extensions?.code === "error.forbidden";
  }

  handle(
    error: GraphQLError
  ): void | Observable<
    FetchResult<Record<string, any>, Record<string, any>, Record<string, any>>
  > {
    // @ts-ignore
    console.log(error);
  }
}

export class InputValidationErrorHandler implements GraphQLErrorMatchHandler {
  match(error: GraphQLError): boolean {
    return error.extensions?.classification === "ValidationError";
  }

  handle(
    error: GraphQLError
  ): void | Observable<
    FetchResult<Record<string, any>, Record<string, any>, Record<string, any>>
  > {
    // @ts-ignore
    console.log(error);
  }
}

export class ServerErrorHandler implements GraphQLErrorMatchHandler {
  match(error: GraphQLError): boolean {
    // @ts-ignore
    return error !== undefined;
  }

  handle(
    error: GraphQLError
  ): void | Observable<
    FetchResult<Record<string, any>, Record<string, any>, Record<string, any>>
  > {
    console.log(JSON.stringify(error));
    message.error(error.message);
  }
}

export class DefaultGraphQLErrorHandler implements GraphQLErrorMatchHandler {
  match(error: GraphQLError): boolean {
    // @ts-ignore
    return error !== undefined;
  }

  // eslint-disable n/handle-callback-err
  handle(
    error: GraphQLError
  ): void | Observable<
    FetchResult<Record<string, any>, Record<string, any>, Record<string, any>>
  > {
    message.error("网络错误!");
    console.log(error);
    console.log({
      position: "bottom",
      statusBarHeight: 20,
      message: "网络错误",
      type: "danger",
      duration: 3000,
    });
  }
}
